package com.xxl.job.executor.sample.frameless.test.wait_notifyDemo;

public class Difficult2 {

    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    //解决了其它干活的线程阻塞的问题
    //但如果有其它线程也在等待条件呢？
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                System.out.println(Thread.currentThread().getName() + "：有烟没？" + hasCigarette);
                if(!hasCigarette) {
                    System.out.println(Thread.currentThread().getName() + ":没烟，先歇会儿！");
                    try {
                        room.wait(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + ":有烟没？" + hasCigarette);
                if (hasCigarette) {
                    System.out.println(Thread.currentThread().getName() + ":可以开始干活了！");
                }
            }
        },"小王").start();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                synchronized (room) {
                    System.out.println(Thread.currentThread().getName() + ":可以开始干活了！");
                }
            },"其他人").start();
        }
        Thread.sleep(1000);
        new Thread(() -> {
            synchronized (room) {
                hasCigarette = true;
                System.out.println(Thread.currentThread().getName() + ":烟到了！");
                room.notify();
            }
        },"送烟的").start();
    }
}
